package ourfilter;

import java.io.StreamCorruptedException;

import javax.media.jai.JAI;

import ourImage.OurPlanarImage;
import pimpmypipe.filter.ForwardingFilter;
import pimpmypipe.interfaces.Readable;
import pimpmypipe.interfaces.Writeable;
import pimpmypipe.pipe.Pipe;
/**
 * This Filter saves the result of the filtered image to a file
 * 
 * see OUT_IMAGE
 * 
 * @author Benjamin
 */
public class SaveFilter extends ForwardingFilter<OurPlanarImage> {
    
    private String _outFile = "filteredImage";
    private boolean _filterEnabled = false;
    
    
    public SaveFilter(Pipe<OurPlanarImage> in, Pipe<OurPlanarImage> out){
        super(in, out);
        in.setOut(this);
        out.setIn(this);   
    }
    public SaveFilter(Readable<OurPlanarImage> in, Writeable<OurPlanarImage> out){
        super(in, out);
    }

    @Override
    public void write(OurPlanarImage value) throws StreamCorruptedException {
        saveImage(value);
        super.write(value);
    }

    @Override
    public OurPlanarImage read() throws StreamCorruptedException {
        OurPlanarImage img = super.read();
        saveImage(img);
        return img;
    }
    
    /**
     * Save the given image (entity) to a file
     * @param entity 
     */
    private void saveImage(OurPlanarImage entity){
        if (_filterEnabled) {
            if (entity != null) {
                // Bug: file still open after write
                JAI.create("filestore", entity.getImage(), _outFile, "JPEG");
            }
        }
    }

    public String getOutFile() {
        return _outFile;
    }

    public void setOutFile(String outFile) {
        _outFile = outFile;
    }

    public boolean isEnabled() {
        return _filterEnabled;
    }

    public void setFilterEnabled(boolean enabled) {
        _filterEnabled = enabled;
    }
    
}
